package org.tinygame.herostory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


/**
 * MySql会话工厂
 * @author shkstart
 * @create 2022-05-07 15:39
 */
public final class MySqlSessionFactory {
    private static SqlSessionFactory _sqlSessionFactory;

    /**
     * 私有默认构造器
     */
    private MySqlSessionFactory(){}

    /**
     * 初始化
     */
    public static void init(){
        try {
            _sqlSessionFactory=(new SqlSessionFactoryBuilder()).
                    build(Resources.getResourceAsStream("MyBatisConfig.xml"));
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 开启mysql会话
     * @return
     */
    public static SqlSession openSession(){
        if(null==_sqlSessionFactory){
            throw new RuntimeException("_sqlSessionFactory未初始化");
        }
        return _sqlSessionFactory.openSession(true);
    }

}
